<template>
  <div>
    <h2>Email Tasks</h2>

    <div class="action-buttons">
      <el-button type="primary" @click="showCreateDialog">Create Task</el-button>
    </div>

    <!-- Email Tasks Table -->
    <el-table :data="tasks" style="width: 100%; margin-top: 20px;" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="taskName" label="Task Name" width="200"></el-table-column>
      <el-table-column prop="subject" label="Subject" width="200"></el-table-column>
      <el-table-column prop="targetGroup" label="Target Group" width="150"></el-table-column>
      <el-table-column label="Status" width="120">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Progress" width="200">
        <template slot-scope="scope">
          <el-progress
            :percentage="getProgressPercentage(scope.row)"
            :status="getProgressStatus(scope.row)">
          </el-progress>
          <div class="task-progress">
            {{ scope.row.successCount || 0 }}/{{ scope.row.totalCount || 0 }} sent
            <span v-if="scope.row.failCount > 0" style="color: #F56C6C;">
              ({{ scope.row.failCount }} failed)
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Actions" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="executeTask(scope.row)"
            :disabled="scope.row.status === 1 || scope.row.status === 2">
            Execute
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">
            Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Pagination -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px;">
    </el-pagination>

    <!-- Create Task Dialog -->
    <el-dialog title="Create Email Task" :visible.sync="createDialogVisible" width="800px">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="Task Name" prop="taskName">
          <el-input v-model="form.taskName" placeholder="Enter task name"></el-input>
        </el-form-item>

        <el-form-item label="Target Group" prop="targetGroup">
          <el-select v-model="form.targetGroup" placeholder="Select target group" style="width: 100%;">
            <el-option
              v-for="group in groups"
              :key="group"
              :label="group"
              :value="group">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="Use Template">
          <el-switch v-model="useTemplate"></el-switch>
        </el-form-item>

        <template v-if="useTemplate">
          <el-form-item label="Template" prop="templateId">
            <el-select v-model="form.templateId" placeholder="Select template" style="width: 100%;" @change="handleTemplateChange">
              <el-option
                v-for="template in templates"
                :key="template.id"
                :label="template.templateName"
                :value="template.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Variables" v-if="form.templateId">
            <el-form :inline="true">
              <el-form-item v-for="(value, key) in form.templateVariables" :key="key" :label="key">
                <el-input v-model="form.templateVariables[key]"></el-input>
              </el-form-item>
            </el-form>
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="Subject" prop="subject">
            <el-input v-model="form.subject" placeholder="Enter email subject"></el-input>
          </el-form-item>

          <el-form-item label="Content" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="10" placeholder="Enter email content (HTML supported)"></el-input>
          </el-form-item>
        </template>

        <el-form-item label="Schedule">
          <el-switch v-model="useSchedule"></el-switch>
        </el-form-item>

        <el-form-item label="Schedule Time" v-if="useSchedule" prop="scheduledTime">
          <el-date-picker
            v-model="form.scheduledTime"
            type="datetime"
            placeholder="Select date and time"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Create</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EmailTasks',
  data() {
    return {
      tasks: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      createDialogVisible: false,
      useTemplate: false,
      useSchedule: false,
      form: {
        taskName: '',
        subject: '',
        content: '',
        targetGroup: '',
        templateId: null,
        templateVariables: {},
        scheduledTime: null
      },
      rules: {
        taskName: [
          { required: true, message: 'Please enter task name', trigger: 'blur' }
        ],
        targetGroup: [
          { required: true, message: 'Please select target group', trigger: 'change' }
        ],
        subject: [
          { required: true, message: 'Please enter email subject', trigger: 'blur' }
        ],
        content: [
          { required: true, message: 'Please enter email content', trigger: 'blur' }
        ],
        templateId: [
          { required: true, message: 'Please select a template', trigger: 'change' }
        ],
        scheduledTime: [
          { required: true, message: 'Please select schedule time', trigger: 'change' }
        ]
      },
      groups: [],
      templates: [],
      refreshInterval: null
    };
  },
  created() {
    this.loadTasks();
    this.loadGroups();
    this.loadTemplates();

    // Set up auto-refresh for task status
    this.refreshInterval = setInterval(() => {
      // Only refresh tasks that are currently in progress
      this.refreshInProgressTasks();
    }, 5000); // Refresh every 5 seconds
  },
  beforeDestroy() {
    // Clear the refresh interval when component is destroyed
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  },
  methods: {
    loadTasks() {
      this.loading = true;
      this.$axios.get(`/email-tasks?page=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          // Make sure we only display non-deleted tasks
          this.tasks = response.data.records.filter(task => task.deleted !== 1);
          this.total = response.data.total;
          this.loading = false;
        })
        .catch(error => {
          console.error('Error loading tasks:', error);
          this.$message.error('Failed to load email tasks');
          this.loading = false;
        });
    },

    loadGroups() {
      this.$axios.get('/email-addresses/groups')
        .then(response => {
          this.groups = response.data;
        })
        .catch(error => {
          console.error('Error loading groups:', error);
          this.$message.error('Failed to load groups');
        });
    },

    loadTemplates() {
      this.$axios.get('/email-templates')
        .then(response => {
          this.templates = response.data.records;
        })
        .catch(error => {
          console.error('Error loading templates:', error);
          this.$message.error('Failed to load templates');
        });
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.loadTasks();
    },

    handleCurrentChange(page) {
      this.currentPage = page;
      this.loadTasks();
    },

    showCreateDialog() {
      this.createDialogVisible = true;
      this.useTemplate = false;
      this.useSchedule = false;
      this.form = {
        taskName: '',
        subject: '',
        content: '',
        targetGroup: '',
        templateId: null,
        templateVariables: {},
        scheduledTime: null
      };
    },

    handleTemplateChange(templateId) {
      // Find the selected template
      const template = this.templates.find(t => t.id === templateId);
      if (!template) return;

      // Extract variables from template
      this.form.templateVariables = {};
      const variableRegex = /{{(.*?)}}/g;
      let match;

      const combinedText = template.subject + template.content;
      while ((match = variableRegex.exec(combinedText)) !== null) {
        const variable = match[1].trim();
        if (!this.form.templateVariables[variable]) {
          this.form.templateVariables[variable] = '';
        }
      }
    },

    executeTask(task) {
      this.$confirm('Are you sure you want to execute this task?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        this.$axios.post(`/email-tasks/${task.id}/execute`)
          .then(() => {
            this.$message.success('Task execution started');
            // Update the task status
            task.status = 1; // In Progress
          })
          .catch(error => {
            console.error('Error executing task:', error);
            this.$message.error('Failed to execute task');
          });
      }).catch(() => {
        // User cancelled
      });
    },

    handleDelete(row) {
      this.$confirm('Are you sure you want to delete this task?', 'Warning', {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/email-tasks/${row.id}`)
          .then(() => {
            this.$message.success('Task deleted successfully');
            // Immediately remove the task from the local array
            this.tasks = this.tasks.filter(task => task.id !== row.id);
            // Also refresh the task list from the server
            this.loadTasks();
          })
          .catch(error => {
            console.error('Error deleting task:', error);
            this.$message.error('Failed to delete task');
          });
      }).catch(() => {
        // User cancelled
      });
    },

    submitForm() {
      // Adjust validation rules based on form state
      if (this.useTemplate) {
        this.$refs.form.clearValidate(['subject', 'content']);
      } else {
        this.$refs.form.clearValidate(['templateId']);
      }

      if (!this.useSchedule) {
        this.$refs.form.clearValidate(['scheduledTime']);
      }

      this.$refs.form.validate(valid => {
        if (valid) {
          // Prepare the form data
          const formData = { ...this.form };

          // Convert scheduledTime to ISO string if it exists
          if (formData.scheduledTime) {
            formData.scheduledTime = new Date(formData.scheduledTime).toISOString();
          } else {
            delete formData.scheduledTime;
          }

          // Remove template-related fields if not using template
          if (!this.useTemplate) {
            delete formData.templateId;
            delete formData.templateVariables;
          }

          this.$axios.post('/email-tasks', formData)
            .then(() => {
              this.$message.success('Task created successfully');
              this.createDialogVisible = false;
              this.loadTasks();
            })
            .catch(error => {
              console.error('Error creating task:', error);
              this.$message.error('Failed to create task');
            });
        }
      });
    },

    getStatusText(status) {
      switch (status) {
        case 0: return 'Created';
        case 1: return 'In Progress';
        case 2: return 'Completed';
        case 3: return 'Failed';
        default: return 'Unknown';
      }
    },

    getStatusType(status) {
      switch (status) {
        case 0: return 'info';
        case 1: return 'warning';
        case 2: return 'success';
        case 3: return 'danger';
        default: return 'info';
      }
    },

    getProgressPercentage(task) {
      if (!task.totalCount || task.totalCount === 0) return 0;
      const sent = (task.successCount || 0) + (task.failCount || 0);
      return Math.round((sent / task.totalCount) * 100);
    },

    getProgressStatus(task) {
      if (task.status === 3) return 'exception';
      if (task.status === 2) return 'success';
      return '';
    },

    refreshInProgressTasks() {
      // Only refresh tasks that are in progress (status = 1)
      const inProgressTasks = this.tasks.filter(task => task.status === 1);

      if (inProgressTasks.length === 0) {
        return; // No tasks in progress, no need to refresh
      }

      // For each in-progress task, get the latest status
      inProgressTasks.forEach(task => {
        this.$axios.get(`/email-tasks/${task.id}`)
          .then(response => {
            const updatedTask = response.data;
            // Find and update the task in the local array
            const index = this.tasks.findIndex(t => t.id === updatedTask.id);
            if (index !== -1) {
              this.tasks.splice(index, 1, updatedTask);
            }
          })
          .catch(error => {
            console.error(`Error refreshing task ${task.id}:`, error);
            // If we get a 404, the task might have been deleted
            if (error.response && error.response.status === 404) {
              // Remove the task from the local array
              this.tasks = this.tasks.filter(t => t.id !== task.id);
            }
          });
      });
    }
  }
}
</script>
